package ext.tianma.util;

import java.util.StringTokenizer;

import wt.folder.Folder;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.org.WTPrincipal;
import wt.session.SessionHelper;
import wt.util.WTException;

public class FolderUtil {

    public static Folder getFolder(String strFolder, WTContainer wtcontainer) throws WTException {
        WTContainerRef wtcontainerRef = WTContainerRef.newWTContainerRef(wtcontainer);
        return getFolder(strFolder, wtcontainerRef);
    }

    public static Folder getFolder(String strFolder, WTContainerRef wtcontainerRef) throws WTException {
        WTPrincipal curUser = SessionHelper.manager.getPrincipal();
        Folder folder = null;
        try {
            SessionHelper.manager.setAdministrator();
            if (strFolder == null || "".equals(strFolder)) {
                strFolder = "/Default";
            } else if (!strFolder.startsWith("/Default")) {
                strFolder = "/Default/" + strFolder;
            }
            
            StringTokenizer tokenizer = new StringTokenizer(strFolder, "/");
            String subPath = "";
            while (tokenizer.hasMoreTokens()) {
                String token = tokenizer.nextToken();
                subPath = subPath + "/" + token;
                try {
                    folder = wt.folder.FolderHelper.service.getFolder(subPath, wtcontainerRef);
                } catch (WTException e) {
                    folder = wt.folder.FolderHelper.service.createSubFolder(subPath, wtcontainerRef);
                }
            }
        } finally {
            SessionHelper.manager.setPrincipal(curUser.getName());
        }
        return folder;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}
